package com.ruoyi.web.wx.controller;


import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.util.StringUtils;
import com.riversoft.weixin.common.oauth2.AccessToken;
import com.riversoft.weixin.mp.base.AppSetting;
import com.riversoft.weixin.mp.care.Accounts;
import com.riversoft.weixin.mp.oauth2.MpOAuth2s;
import com.riversoft.weixin.pay.base.PaySetting;
import com.riversoft.weixin.pay.redpack.RedPacks;
import com.riversoft.weixin.pay.redpack.bean.RedPackRequest;
import com.riversoft.weixin.pay.redpack.bean.RedPackResponse;
import com.riversoft.weixin.pay.redpack.bean.RedPackResult;
import com.ruoyi.web.wx.entity.*;
import com.ruoyi.web.wx.service.*;
import com.ruoyi.web.wx.utils.CommonUtil;
import com.ruoyi.web.wx.utils.JwtUtil;
import com.ruoyi.web.wx.utils.LockerPool;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("wx")
public class wxApiGzh {
    @Autowired
    private AppInfo appInfo;
    @Autowired
    private IWxUserService wxUserService;
    @Autowired
    private IWxGzhService wxGzhService;
    @Autowired
    private  ICashOutService cashOutService;
    @Autowired
    private  IEnvirBonusTotalService envirBonusTotalService;
    @Autowired
    private LockerPool pool;
    @RequestMapping("officialAccountBind")
    @ApiOperation(value = "公众号绑定unionid")
    public void officialAccountBind( HttpServletRequest request, HttpServletResponse response) throws Exception {
        AppSetting appSetting = new AppSetting();
        String appid = appInfo.getOfficialAccountAppid();
        String appSecret = appInfo.getOfficialAccountSecret();

        appSetting.setAppId(appid);
        appSetting.setSecret(appSecret);
        AppSetting.setDefault(appSetting);
        String url = MpOAuth2s.defaultOAuth2s().authenticationUrl(appInfo.getOfficialAccountAuthCallBackUrl(), "snsapi_userinfo");
        url+="&connect_redirect=1";
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("doOfficialAccountBind")
    @ApiOperation(value = "微信授权回调接口")
    public void doOfficialAccountBind(HttpServletRequest request, HttpServletResponse response) throws Exception {
        AppSetting appSetting = new AppSetting();
        appSetting.setAppId(appInfo.getOfficialAccountAppid());
        appSetting.setSecret(appInfo.getOfficialAccountSecret());
        AppSetting.setDefault(appSetting);

        Map<String, String[]> parameterMap = request.getParameterMap();
        String[] codes = parameterMap.get("code");
        String code = codes[0];
        AccessToken accessToken = MpOAuth2s.defaultOAuth2s().getAccessToken(code);
        String openId = accessToken.getOpenId();
        String unionId = accessToken.getUnionId();
        System.out.println("openid:"+openId+"-------------unionId:"+unionId);
       WxGzh wxGzh = new WxGzh();
        Integer res = -1;
    if(openId!=null&&unionId!=null){
            wxGzh.setOpenid(openId);
            wxGzh.setUnionid(unionId);
        List<WxGzh> wxGzhs = wxGzhService.selectWxGzhList(wxGzh);
        if(wxGzhs!=null&&wxGzhs.size()>0){
                res = 1;
            }else {
            wxGzh.setId(CommonUtil.getUUID());
            wxGzhService.insertWxGzh(wxGzh);
                res = 0;
            }
        }
        response.sendRedirect(appInfo.getBindSuccessCallBackUrl()+"?status="+res);
    }

    @RequestMapping("cashOut")
    @ResponseBody
    public  Map platFormLogin(double cashWithdrawal,HttpServletRequest request) throws Exception {
        Map map = new HashMap();
        String token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        WxUser wxUser = wxUserService.selectWxUserByOpenId(userId);
        if (wxUser == null) {
            map.put("status", "0");
            map.put("message", "没有相关用户信息");
            return map;
        }
        userId= wxUser.getId();
        //判断用户提现金额是否大于自己的所有金额
        double totalMoney = wxUser.getTotalMoney();
        if (cashWithdrawal > totalMoney) {
            map.put("status", "0");
            map.put("message", "可用余额不足");
            return map;
        }
        Double amount = cashWithdrawal;
        //每次提现金额
        double oneDayWithDrawAmount = appInfo.getOneDayWithDrawAmount();
        if (amount == null || amount < 1 || amount > oneDayWithDrawAmount) {
            map.put("status", "0");
            map.put("message", "提现金额不正确");
            return map;
        }
        String openIdApp = wxUser.getOpenId();
        String unionId = wxUser.getUnionId();
        if (StringUtils.isNullOrEmpty(openIdApp) || StringUtils.isNullOrEmpty(unionId)) {
            map.put("status", "0");
            map.put("message", "用户信息有误");
            return map;
        }
        //判断是否绑定过公众号
        WxGzh wxGzh = new WxGzh();
        wxGzh.setUnionid(unionId);
        List<WxGzh> wxGzhs = wxGzhService.selectWxGzhList(wxGzh);
        if (wxGzhs == null || wxGzhs.size() <= 0) {
            map.put("status", "0");
            map.put("message", "请先在公众号【河北慧居生活】中绑定小程序");
            return map;
        }
        //公众号openId
        WxGzh wxGzh1 = wxGzhs.get(0);
        String openId = wxGzh1.getOpenid();
        String locker = pool.getLocker(String.valueOf(wxUser.getId()));
        synchronized (locker) {
            System.out.println(Thread.currentThread().getName() + "进入体现环节");
            //查看用户今天提现了多少次
            Integer todayWithdrawCount = cashOutService.selectTotalCount(userId);
            if(todayWithdrawCount==null){
                todayWithdrawCount=0;
            }
            Integer oneDayWithDrawCount = appInfo.getOneDayWithDrawCount();
            if (todayWithdrawCount >= oneDayWithDrawCount) {
                map.put("status", "0");
                map.put("message", "每天提现次数不能超过" + oneDayWithDrawCount + ",今日已提现" + todayWithdrawCount + "次");
                return map;
            }
            String MCHId = appInfo.getPayMchid();
            RedPackRequest redPackRequest = new RedPackRequest();
            Double v1 = amount * 100;
            int i = v1.intValue();
            redPackRequest.setActivityName("环保金提现");
            redPackRequest.setAmount(i);

            Random r = new Random(1);
            int i1 = r.nextInt(100);
            String orderNum = CommonUtil.generatorOrderNumber(MCHId);
            redPackRequest.setBillNumber(orderNum);
            redPackRequest.setNumber(1);
            redPackRequest.setOpenId(openId);
            redPackRequest.setRemark("地球将铭记");
            redPackRequest.setWishing("感谢您为环保事业做出的贡献");
            redPackRequest.setClientIp("127.0.0.1");
            redPackRequest.setSendName("环保金");
            redPackRequest.setAppId(appInfo.getOfficialAccountAppid());
            PaySetting paySetting = new PaySetting();
            paySetting.setAppId(appInfo.getOfficialAccountAppid());
            paySetting.setMchId(appInfo.getPayMchid());
            paySetting.setKey(appInfo.getPayApikey());
            paySetting.setCertPath(appInfo.getPayCertPath());
            paySetting.setCertPassword(appInfo.getPayCertPassword());
            PaySetting.setDefault(paySetting);
            RedPackResponse redPackResponse = RedPacks.defaultRedPacks().sendSingle(redPackRequest);
            if (redPackResponse.getResultCode().equals("SUCCESS") && redPackResponse.getReturnCode().equals("SUCCESS")) {
                //成功提现 增加提现记录  更新用户环保金钱数
                CashOut cashOut = new CashOut();
                cashOut.setId(CommonUtil.getUUID());
                cashOut.setOrderNum(orderNum);
                cashOut.setCashWithdrawal(amount);
                cashOut.setStatus("1");
                cashOut.setWxUserId(userId);
                cashOut.setCreateTime(new Date());
                cashOutService.insertCashOut(cashOut);
                wxUser.setTotalMoney(totalMoney - amount);
                wxUserService.updateWxUser(wxUser);
                EnvirBonusTotal envirBonusTotal = new EnvirBonusTotal();
                envirBonusTotal.setMoney(amount);
                envirBonusTotal.setCreateTime(new Date());
                envirBonusTotal.setType("2");
                envirBonusTotal.setWxUserId(userId);
                envirBonusTotal.setId(CommonUtil.getUUID());
                envirBonusTotal.setSource("2");
                envirBonusTotalService.insertEnvirBonusTotal(envirBonusTotal);
                map.put("status",1);
                return  map;
            } else if (redPackResponse.getResultCode().equals("FAIL") && redPackResponse.getReturnCode().equals("SUCCESS")) {
                RedPacks redPacks = RedPacks.defaultRedPacks();
                RedPackResult query = redPacks.query(orderNum);
                String status = query.getStatus();
                System.out.println("-------------" + status + "=================");
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(status)){
                    if(!WithdrawalStatus.WX_RECEIVED.getInfo().equals(status)&&!WithdrawalStatus.WX_SENT.getInfo().equals(status)&&!WithdrawalStatus.WX_SENDING.getInfo().equals(status)){
                        //record.setStatus(WithdrawalStatus.Error.getStatusNum());
                        //withdrawalRecordService.insertWithdrawalRecord(record);
                        map.put("status",0);
                        map.put("message","提现失败请稍后再试");
                    }else {
                        //成功提现 增加提现记录  更新用户环保金钱数
                        CashOut cashOut = new CashOut();
                        cashOut.setId(CommonUtil.getUUID());
                        cashOut.setOrderNum(orderNum);
                        cashOut.setCashWithdrawal(amount);
                        cashOut.setStatus("1");
                        cashOut.setWxUserId(userId);
                        cashOut.setCreateTime(new Date());
                        cashOutService.insertCashOut(cashOut);
                        wxUser.setTotalMoney(totalMoney - amount);
                        wxUserService.updateWxUser(wxUser);
                        EnvirBonusTotal envirBonusTotal = new EnvirBonusTotal();
                        envirBonusTotal.setMoney(amount);
                        envirBonusTotal.setCreateTime(new Date());
                        envirBonusTotal.setType("2");
                        envirBonusTotal.setWxUserId(userId);
                        envirBonusTotal.setId(CommonUtil.getUUID());
                        envirBonusTotal.setSource("2");
                        envirBonusTotalService.insertEnvirBonusTotal(envirBonusTotal);
                        map.put("status",1);
                        return  map;
                    }
                }
                return  map;
            }else {
                map.put("status",0);
                map.put("message","提现失败请稍后再试");
            }
            return map;
        }
    }
    @RequestMapping("cashOutHistory")
    @ResponseBody
    public   List<EnvirBonusTotal> cashOutHistory(HttpServletRequest request)  {
        String token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        WxUser wxUser = wxUserService.selectWxUserByOpenId(userId);
        if (wxUser==null){
            return null;
        }
        EnvirBonusTotal envirBonusTotal = new EnvirBonusTotal();
        envirBonusTotal.setWxUserId(wxUser.getId());
        List<EnvirBonusTotal> envirBonusTotals = envirBonusTotalService.selectEnvirBonusTotalList(envirBonusTotal);
        return envirBonusTotals;
    }


}
